<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UserModel
 *
 * @author Marko
 */
class Utils extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public static function est_event_raw_string(Event $event, $short = false) {
        
        if ($short) {
            $result =  ($event->isRelay() == 0 ? $event->getDistance() : '4x' . $event->getDistance()/4) 
                . ' m ' .
                Utils::est_stroke($event->getStroke(), 0, true);
            
            return $result;
        }
        
        $result = '#' . $event->getNr() . ' ' . Utils::est_gender_string($event->getGender())
                . ' ' . Utils::est_age_string($event->getLowAge(), $event->getHighAge()) . ' ' .
                ($event->isRelay() == 0 ? $event->getDistance() : '4x' . $event->getDistance()/4) 
                . ' meetrit ' .
                Utils::est_stroke($event->getStroke(), $event->isRelay()) . ' ' . Utils::est_event_type_string($event->getType());
        return strtolower(str_replace('  ', ' ', $result));
    }
    
    public static function est_event_type_string($event_type) {
        switch (strtoupper($event_type)) {
            case ('F'): return 'finaal';
            case ('P'): return 'eelujumine';
            case ('SO'): return 'ümberujumine';
            default : return '';
        }
    }
    
     public static function est_age_string($low_age, $high_age) {
        if ($low_age == 0 && $high_age == 109) {
            return '';
        } else if ($low_age == 0 || $low_age == 109) {
            return $high_age . ' & nooremad';
        } else if ($high_age == 0 || $high_age == 109) {
            return $low_age . ' & vanemad';
        } else if ($high_age == $low_age) {
            return $low_age . ' aastased';
        } else {
            return $low_age . ' - ' . $high_age . ' aastased';
        }
    }

    public static function est_gender_string($gender) {
        switch (strtoupper($gender)) {
            case ('M'): return 'mehed';
            case ('F'): return 'naised';
            case ('X'): return 'sega';
            default : return '';
        }
    }

    public static function est_stroke($stroke, $relay = false, $short = false) {
        $result = '';
        switch (strtolower($stroke)) {
            case 'free':
                $result = $relay ? 'vabalt teate' : 'vabalt';
                break;
            case 'back':
                $result = 'selili';
                break;
            case 'breast':
                $result = 'rinnuli';
                break;
            case 'fly':
                $result = $short ? 'liblikat' : 'liblik';
                break;
            case 'medley':
                $result = $relay ? 'kombineeritud teate' : 'kompleks';
                $result = $short ? 'kompleksi' : $result;
                break;
            default:
                $result = '';
                break;
        }

        return ($short ? $result : $result . 'ujumine');
    }

    public static function est_date($date) {
        return date('d.m.Y', strtotime($date));
    }

    public function encode_array(&$item) {
        $item = utf8_encode($item);
    }

    public function utf8_encode_array(array &$data) {
        array_walk_recursive($data, array($this, 'encode_array'));
    }

    public static function generate_split_query($distance, $lower_case = false) {
        if ($distance <= 50)
            return '';
        $splits = $distance / 50;
        $query = ',';
        for ($i = 1; $i <= $splits; $i++) {
            if ($i == $splits) {
                $query.= "`Split_$i`";
            } else {
                $query.= "`Split_$i`, ";
            }
        }
        if ($lower_case) {
            return strtolower($query);
        }
        return $query;
    }

    public static function utf8_encode_deep(&$input) {
        if (is_string($input)) {
            $input = utf8_encode($input);
        } else if (is_array($input)) {
            foreach ($input as &$value) {
                Utils::utf8_encode_deep($value);
            }

            unset($value);
        } else if (is_object($input)) {
            $vars = array_keys(get_object_vars($input));

            foreach ($vars as $var) {
                Utils::utf8_encode_deep($input->$var);
            }
        }
    }

    public static function trim_deep(&$input) {
        if (is_string($input)) {
            $input = trim($input);
        } else if (is_array($input)) {
            foreach ($input as &$value) {
                Utils::trim_deep($value);
            }

            unset($value);
        } else if (is_object($input)) {
            $vars = array_keys(get_object_vars($input));

            foreach ($vars as $var) {
                Utils::trim_deep($input->$var);
            }
        }
    }

    public function mdb_connetion_from_full_path($full_path) {
        $db_config['username'] = "ADODB.Connection";
        $db_config['password'] = "";
        $db_config['dbdriver'] = "odbc";
        $db_config['dbprefix'] = "";
        $db_config['pconnect'] = FALSE;
        $db_config['db_debug'] = TRUE;
        $db_config['cache_on'] = FALSE;
        $db_config['cachedir'] = "";
        $db_config['char_set'] = "utf8";
        $db_config['dbcollat'] = "utf8_general_ci";
        $db_config['database'] = "$full_path";
        $db_config['hostname'] = "DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=$full_path";
        return $this->load->database($db_config, TRUE);
    }
    
    public function sqlite_connetion_from_full_path($full_path) {
        $db_config['username'] = "";
        $db_config['password'] = "";
        $db_config['dbdriver'] = "sqlite";
        $db_config['dbprefix'] = "";
        $db_config['pconnect'] = TRUE;
        $db_config['db_debug'] = TRUE;
        $db_config['cache_on'] = FALSE;
        $db_config['cachedir'] = "";
        $db_config['char_set'] = "utf8";
        $db_config['dbcollat'] = "utf8_general_ci";
        $db_config['database'] = "$full_path";
        $db_config['hostname'] = "localhost";
        print_r($db_config);
        return $this->load->database($db_config, TRUE);
    }

    public function result_to_ms($result_string) {

        if (strpos($result_string, 'DQ') !== false) {
            return MAX_INT;
        }

        $ms = 0.0;
        $result_string = str_replace(',', '.', $result_string);
        $result_string = str_replace('X', '', $result_string);
        $splits = explode(':', $result_string);
        if (count($splits) == 2) {
            $ms += (int) $splits[0] * 60 + (double) $splits[1];
        } else if (count($splits) == 1) {
            $ms += (double) $splits[0];
        } else {
            return MAX_INT;
        }

        return $ms * 1000.0;
    }

    public function result_float_to_ms($float) {
        if ($float == 0 || $float == 'DQ')
            return MAX_INT;
        return (int) ($float * 1000.0);
    }

    public static function change_array_key_case(&$array, $case = CASE_LOWER, $flag_rec = false) {
        $array = array_change_key_case($array, $case);
        if ($flag_rec) {
            foreach ($array as $key => $value) {
                if (is_array($value)) {
                    Utils::change_array_key_case($array[$key], $case, true);
                }
            }
        }
    }

    public function ms_to_result_string($ms, $seed = false) {
        if ($ms == MAX_INT)
            return $seed ? 'NT' : 'DQ';
        $h = $ms / 10 % 100;
        $m = floor($ms / 1000 / 60);
        $s = floor($ms / 1000 % 60);
        $hundreds = ($h < 10) ? '0' . $h : $h;
        $seconds = ($s < 10) ? '0' . $s : $s;
        $minutes = ($m > 0) ? $m . ':' : '';
        return $minutes . $seconds . ',' . $hundreds;
    }

    public function result_float_to_string($float, $seed = false) {
        return $this->ms_to_result_string($this->result_float_to_ms($float), $seed);
    }

    public static function stroke_to_est($stroke) {
        if ($stroke == 'free') {
            return 'vabaujumine';
        } else if ($stroke == 'breast') {
            return 'rinnuliujumine';
        } else if ($stroke == 'back') {
            return 'seliliujumine';
        } else if ($stroke == 'fly') {
            return 'liblikujumine';
        } else if ($stroke == 'medley') {
            return 'kompleksujumine';
        } else {
            return 'tuvastamata';
        }
    }

    public static function gender_to_est($gender) {
        if ($gender === 'X') {
            return 'sega';
        } else {
            return ($gender === 'M' ? ' mehed' : ' naised');
        }
    }

    public static function country_dropdown($name = "country", $top_countries = array(), $selection = NULL, $show_all = TRUE) {
        // You may want to pull this from an array within the helper
        $countries = Utils::getCountryArray();

        $html = "<select name='{$name}'>";
        $selected = NULL;
        if (in_array($selection, $top_countries)) {
            $top_selection = $selection;
            $all_selection = NULL;
        } else {
            $top_selection = NULL;
            $all_selection = $selection;
        }

        if (!empty($top_countries)) {
            $html .= "<optgroup label='Lemmik riigid'>";
            foreach ($top_countries as $value) {
                if (array_key_exists($value, $countries)) {
                    if ($value === $top_selection) {
                        $selected = "SELECTED";
                    }
                    $html .= "<option value='{$value}' {$selected}>{$countries[$value]}</option>";
                    $selected = NULL;
                }
            }
            $html .= "</optgroup>";
        }

        if ($show_all) {
            $html .= "<optgroup label='Kõik riigid'>";
            foreach ($countries as $key => $country) {
                if ($key === $all_selection) {
                    $selected = "SELECTED";
                }
                $html .= "<option value='{$key}' {$selected}>{$country}</option>";
                $selected = NULL;
            }
            $html .= "</optgroup>";
        }

        $html .= "</select>";
        return $html;
    }

    public static function getCountryName($country_code) {
        $country_array = Utils::getCountryArray();
        return $country_array["$country_code"];
    }

    public static function getCountryArray() {
        return array(
            "AF" => "Afghanistan",
            "AL" => "Albania",
            "DZ" => "Algeria",
            "AD" => "Andorra",
            "AO" => "Angola",
            "AI" => "Anguilla",
            "AQ" => "Antarctica",
            "AG" => "Antigua and Barbuda",
            "AR" => "Argentina",
            "AM" => "Armenia",
            "AW" => "Aruba",
            "AU" => "Australia",
            "AT" => "Austria",
            "AZ" => "Azerbaijan",
            "BS" => "Bahamas",
            "BH" => "Bahrain",
            "BD" => "Bangladesh",
            "BB" => "Barbados",
            "BY" => "Belarus",
            "BE" => "Belgium",
            "BZ" => "Belize",
            "BJ" => "Benin",
            "BM" => "Bermuda",
            "BT" => "Bhutan",
            "BO" => "Bolivia",
            "BA" => "Bosnia and Herzegovina",
            "BW" => "Botswana",
            "BR" => "Brazil",
            "IO" => "British Indian Ocean",
            "BN" => "Brunei",
            "BG" => "Bulgaria",
            "BF" => "Burkina Faso",
            "BI" => "Burundi",
            "KH" => "Cambodia",
            "CM" => "Cameroon",
            "CA" => "Canada",
            "CV" => "Cape Verde",
            "KY" => "Cayman Islands",
            "CF" => "Central African Republic",
            "TD" => "Chad",
            "CL" => "Chile",
            "CN" => "China",
            "CX" => "Christmas Island",
            "CC" => "Cocos (Keeling) Islands",
            "CO" => "Colombia",
            "KM" => "Comoros",
            "CD" => "Congo, Democratic Republic of the",
            "CG" => "Congo, Republic of the",
            "CK" => "Cook Islands",
            "CR" => "Costa Rica",
            "HR" => "Croatia",
            "CY" => "Cyprus",
            "CZ" => "Czech Republic",
            "DK" => "Denmark",
            "DJ" => "Djibouti",
            "DM" => "Dominica",
            "DO" => "Dominican Republic",
            "TL" => "East Timor",
            "EC" => "Ecuador",
            "EG" => "Egypt",
            "SV" => "El Salvador",
            "GQ" => "Equatorial Guinea",
            "ER" => "Eritrea",
            "EE" => "Eesti",
            "ET" => "Ethiopia",
            "FK" => "Falkland Islands (Malvinas)",
            "FO" => "Faroe Islands",
            "FJ" => "Fiji",
            "FI" => "Soome",
            "FR" => "Prantsusmaa",
            "GF" => "French Guiana",
            "PF" => "French Polynesia",
            "GA" => "Gabon",
            "GM" => "Gambia",
            "GE" => "Georgia",
            "DE" => "Saksamaa",
            "GH" => "Ghana",
            "GI" => "Gibraltar",
            "GR" => "Greece",
            "GL" => "Greenland",
            "GD" => "Grenada",
            "GP" => "Guadeloupe",
            "GT" => "Guatemala",
            "GN" => "Guinea",
            "GW" => "Guinea-Bissau",
            "GY" => "Guyana",
            "HT" => "Haiti",
            "HN" => "Honduras",
            "HK" => "Hong Kong",
            "HU" => "Hungary",
            "IS" => "Iceland",
            "IN" => "India",
            "ID" => "Indonesia",
            "IE" => "Ireland",
            "IL" => "Israel",
            "IT" => "Italy",
            "CI" => "Ivory Coast (C&ocirc;te ;Ivoire)",
            "JM" => "Jamaica",
            "JP" => "Japan",
            "JO" => "Jordan",
            "KZ" => "Kazakhstan",
            "KE" => "Kenya",
            "KI" => "Kiribati",
            "KR" => "Korea, South",
            "KW" => "Kuwait",
            "KG" => "Kyrgyzstan",
            "LA" => "Laos",
            "LV" => "Läti",
            "LB" => "Lebanon",
            "LS" => "Lesotho",
            "LI" => "Liechtenstein",
            "LT" => "Leedu",
            "LU" => "Luxembourg",
            "MO" => "Macau",
            "MK" => "Macedonia, Republic of",
            "MG" => "Madagascar",
            "MW" => "Malawi",
            "MY" => "Malaysia",
            "MV" => "Maldives",
            "ML" => "Mali",
            "MT" => "Malta",
            "MH" => "Marshall Islands",
            "MQ" => "Martinique",
            "MR" => "Mauritania",
            "MU" => "Mauritius",
            "YT" => "Mayotte",
            "MX" => "Mexico",
            "FM" => "Micronesia",
            "MD" => "Moldova",
            "MC" => "Monaco",
            "MN" => "Mongolia",
            "ME" => "Montenegro",
            "MS" => "Montserrat",
            "MA" => "Morocco",
            "MZ" => "Mozambique",
            "NA" => "Namibia",
            "NR" => "Nauru",
            "NP" => "Nepal",
            "NL" => "Holland",
            "AN" => "Netherlands Antilles",
            "NC" => "New Caledonia",
            "NZ" => "New Zealand",
            "NI" => "Nicaragua",
            "NE" => "Niger",
            "NG" => "Nigeria",
            "NU" => "Niue",
            "NF" => "Norfolk Island",
            "NO" => "Norway",
            "OM" => "Oman",
            "PK" => "Pakistan",
            "PS" => "Palestinian Territory",
            "PA" => "Panama",
            "PG" => "Papua New Guinea",
            "PY" => "Paraguay",
            "PE" => "Peru",
            "PH" => "Philippines",
            "PN" => "Pitcairn Island",
            "PL" => "Poland",
            "PT" => "Portugal",
            "QA" => "Qatar",
            "RE" => "R&eacute;union",
            "RO" => "Romania",
            "RU" => "Venemaa",
            "RW" => "Rwanda",
            "SH" => "Saint Helena",
            "KN" => "Saint Kitts and Nevis",
            "LC" => "Saint Lucia",
            "PM" => "Saint Pierre and Miquelon",
            "VC" => "Saint Vincent and the Grenadines",
            "WS" => "Samoa",
            "SM" => "San Marino",
            "ST" => "S&atilde;o Tome and Principe",
            "SA" => "Saudi Arabia",
            "SN" => "Senegal",
            "RS" => "Serbia",
            "CS" => "Serbia and Montenegro",
            "SC" => "Seychelles",
            "SL" => "Sierra Leon",
            "SG" => "Singapore",
            "SK" => "Slovakia",
            "SI" => "Slovenia",
            "SB" => "Solomon Islands",
            "SO" => "Somalia",
            "ZA" => "South Africa",
            "GS" => "South Georgia and the South Sandwich Islands",
            "ES" => "Spain",
            "LK" => "Sri Lanka",
            "SR" => "Suriname",
            "SJ" => "Svalbard and Jan Mayen",
            "SZ" => "Swaziland",
            "SE" => "Rootsi",
            "CH" => "Switzerland",
            "TW" => "Taiwan",
            "TJ" => "Tajikistan",
            "TZ" => "Tanzania",
            "TH" => "Thailand",
            "TG" => "Togo",
            "TK" => "Tokelau",
            "TO" => "Tonga",
            "TT" => "Trinidad and Tobago",
            "TN" => "Tunisia",
            "TR" => "Turkey",
            "TM" => "Turkmenistan",
            "TC" => "Turks and Caicos Islands",
            "TV" => "Tuvalu",
            "UG" => "Uganda",
            "UA" => "Ukraine",
            "AE" => "United Arab Emirates",
            "GB" => "United Kingdom",
            "US" => "United States",
            "UM" => "United States Minor Outlying Islands",
            "UY" => "Uruguay",
            "UZ" => "Uzbekistan",
            "VU" => "Vanuatu",
            "VA" => "Vatican City",
            "VE" => "Venezuela",
            "VN" => "Vietnam",
            "VG" => "Virgin Islands, British",
            "WF" => "Wallis and Futuna",
            "EH" => "Western Sahara",
            "YE" => "Yemen",
            "ZM" => "Zambia",
            "ZW" => "Zimbabwe");
    }

}

?>
